﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using JX.Application;
using JX.Core.Entity;
using JX.Infrastructure;
using JX.Infrastructure.Common;
using JX.Infrastructure.Field;
using JX.Infrastructure.Framework.Authorize;
using JXWebSite.Areas.Admin.Models.UserViewModels;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace JXWebSite.Areas.Admin.Controllers
{
	/// <summary>
	/// 会员管理模块控制器
	/// </summary>
	[Area("Admin")]
	[Route("Admin/[controller]/[action]")]
	[AdminAuthorize]
	public class UserController : Controller
    {
		private IUsersServiceAppDapper _UsersService;
		private IUserGroupsServiceAppDapper _UserGroupsService;
		private INodesServiceAppDapper _NodesService;
		private IModelsServiceAppDapper _ModelsService;
		private IContacterServiceAppDapper _ContacterService;
		private IDictionaryServiceAppDapper _DictionaryServiceApp;
		private ICompanyServiceAppDapper _CompanyService;
		private IBankrollLogServiceAppDapper _BankrollLogService;
		private IExpLogServiceAppDapper _ExpLogService;
		private IPointLogServiceAppDapper _PointLogService;
		private IValidLogServiceAppDapper _ValidLogService;
		/// <summary>
		/// 依赖注入
		/// </summary>
		/// <param name="UsersService"></param>
		/// <param name="UserGroupsService"></param>
		/// <param name="NodesService"></param>
		/// <param name="ModelsService"></param>
		/// <param name="ContacterService"></param>
		/// <param name="DictionaryServiceApp"></param>
		/// <param name="BankrollLogService"></param>
		/// <param name="ExpLogService"></param>
		/// <param name="PointLogService"></param>
		/// <param name="ValidLogService"></param>
		/// <param name="CompanyService"></param>
		public UserController(IUsersServiceAppDapper UsersService,
			IUserGroupsServiceAppDapper UserGroupsService,
			INodesServiceAppDapper NodesService,
			IModelsServiceAppDapper ModelsService,
			IContacterServiceAppDapper ContacterService,
			IDictionaryServiceAppDapper DictionaryServiceApp,
			IBankrollLogServiceAppDapper BankrollLogService,
			IExpLogServiceAppDapper ExpLogService,
			IPointLogServiceAppDapper PointLogService,
			IValidLogServiceAppDapper ValidLogService,
			ICompanyServiceAppDapper CompanyService)
		{
			_UsersService = UsersService;
			_UserGroupsService = UserGroupsService;
			_NodesService = NodesService;
			_ModelsService = ModelsService;
			_ContacterService = ContacterService;
			_DictionaryServiceApp = DictionaryServiceApp;
			_BankrollLogService = BankrollLogService;
			_ExpLogService = ExpLogService;
			_PointLogService = PointLogService;
			_ValidLogService = ValidLogService;
			_CompanyService = CompanyService;
		}

		#region 会员列表
		/// <summary>
		/// 会员列表页面，输出会员组列表
		/// </summary>
		/// <returns></returns>
		[AdminAuthorize(Roles = "SuperAdmin,UserManage")]
		public ActionResult UserManage()
		{
			var result = _UserGroupsService.GetList(p => true);
			return View(result);
		}
		/// <summary>
		/// 得到会员列表的分页数据
		/// </summary>
		/// <returns></returns>
		public IActionResult GetUserList()
		{
			int PageNum = Utility.Query("PageNum", 1);
			int PageSize = Utility.Query("PageSize", 10);
			int GroupID = Utility.Query("GroupID", 0);
			string SearchName = Utility.Query("SearchName");
			string SearchKeyword = Utility.Query("SearchKeyword");
			int TabStatus = Utility.Query("TabStatus", 0);
			string filter = " 1=1 ";
			if (GroupID != 0)
			{
				filter += " and U.GroupID = " + GroupID;
			}
			if (!string.IsNullOrEmpty(SearchKeyword))
			{
				filter += " and " + SearchName + " like '%" + DataSecurity.FilterBadChar(SearchKeyword) + "%'";
			}
			switch (TabStatus)
			{
				case 1://24小时登录的
					filter += " and DATEDIFF(hh, LoginTime, GETDATE()) < 25 ";
					break;
				case 2://24小时注册的
					filter += " and DATEDIFF(hh, RegTime, GETDATE()) < 25 ";
					break;
				case 3://锁定的
					filter += " and UserStatus = 1";
					break;
				case 4://未通过邮件验证的
					filter += " and (UserStatus = 2 or UserStatus = 6) ";
					break;
				case 5://未通过管理员验证的
					filter += " and (UserStatus = 4 or UserStatus = 6) ";
					break;
				case 6://设置了单独权限的
					filter += " and IsInheritGroupRole = 0 ";
					break;
			}
			string strColumn = " U.*,UG.GroupName ";
			string TableName = " Users U inner join UserGroups UG on U.GroupID = UG.GroupID ";
			int RecordTotal;
			var result = _UsersService.GetListPaged<dynamic>(startRowIndexId: (PageNum - 1) * PageSize, maxNumberRows: PageSize,
				StrColumn: strColumn, TableName: TableName, Filter: filter,
				SortColumn: "UserID", Sorts: "desc", out RecordTotal).ToList();
			var pagerModel = new PagerModel<dynamic>(PageNum, PageSize, RecordTotal, result);
			return Json(pagerModel);
		}
		/// <summary>
		/// 选择会员页面，输出会员组列表
		/// </summary>
		/// <returns></returns>
		public IActionResult SelectUser()
		{
			var result = _UserGroupsService.GetList(p => true);
			return View(result);
		}
		#endregion

		#region 会员的删除/更新状态
		/// <summary>
		/// 删除用户及相关权限
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,UserManage")]
		public IActionResult DelUser(int id)
		{
			if (id <= 0)
			{
				return Json(new
				{
					Result = "删除失败！没有指定要删除的记录ID！"
				});
			}
			try
			{
				if (_UsersService.DelUserFull(id))
				{
					return Json(new
					{
						Result = "ok"
					});
				}
				else
				{
					return Json(new
					{
						Result = "删除失败！"
					});
				}
			}
			catch (Exception ex)
			{
				return Json(new
				{
					Result = "删除失败！" + ex.Message
				});
			}
		}
		/// <summary>
		/// 批量删除用户及相关权限
		/// </summary>
		/// <param name="ids"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,UserManage")]
		public IActionResult DelUserMulti(string ids)
		{
			if (string.IsNullOrEmpty(ids))
			{
				return Json(new
				{
					Result = "删除失败！没有指定要删除的记录ID！"
				});
			}
			try
			{
				if (_UsersService.BatchDel(ids))
				{
					return Json(new
					{
						Result = "ok"
					});
				}
				else
				{
					return Json(new
					{
						Result = "删除失败！"
					});
				}
			}
			catch (Exception ex)
			{
				return Json(new
				{
					Result = "删除失败！" + ex.Message
				});
			}
		}
		/// <summary>
		/// 更新会员状态
		/// </summary>
		/// <param name="ids"></param>
		/// <param name="UserStatus"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,AdministratorManage")]
		public IActionResult UpdateUserStatus(string ids, int UserStatus = 1)
		{
			if (string.IsNullOrEmpty(ids))
			{
				return Json(new
				{
					Result = "更新失败！没有指定要操作的记录ID！"
				});
			}
			try
			{
				if (_UsersService.Update("UserStatus=@UserStatus", " and UserID in @ids", new { ids = StringHelper.GetArrayBySplit<int>(ids).ToArray(), UserStatus }))
				{
					return Json(new
					{
						Result = "ok"
					});
				}
				else
				{
					return Json(new
					{
						Result = "更新失败！"
					});
				}
			}
			catch (Exception ex)
			{
				return Json(new
				{
					Result = "更新失败！" + ex.Message
				});
			}
		}
		#endregion

		#region 会员移动
		/// <summary>
		/// 会员移动页面
		/// </summary>
		/// <param name="ids"></param>
		/// <param name="idType"></param>
		/// <returns></returns>
		[AdminAuthorize(Roles = "SuperAdmin,UserMove")]
		public async Task<IActionResult> UserMove(string ids,int idType=0)
		{
			var result = await _UserGroupsService.GetListAsync(p => true);
			UserMoveViewModel userMoveViewModel = new UserMoveViewModel();
			switch (idType)
			{
				case 0:
					userMoveViewModel.ids = ids;
					break;
				case 1:
					userMoveViewModel.UserName = ids;
					break;
				case 2:
					userMoveViewModel.GroupIDs = ids;
					break;
			}
			userMoveViewModel.IdType = idType;
			return View(userMoveViewModel);
		}
		/// <summary>
		/// 会员移动
		/// </summary>
		/// <param name="model"></param>
		/// <param name="collection"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,UserMove")]
		public async Task<ActionResult> UserMove(UserMoveViewModel model = null, IFormCollection collection = null)
		{
			bool bFlag = false;
			switch (model.IdType)
			{
				case 0:
					if (string.IsNullOrWhiteSpace(model.ids))
					{
						ModelState.AddModelError(string.Empty, "会员ID不能为空");
						return View(model);
					}
					bFlag = await _UsersService.UpdateAsync("GroupID=@GroupID", " and UserID in @ids", new { ids = StringHelper.GetArrayBySplit<int>(model.ids).ToArray(), GroupID = model.RightGroupID });
					break;
				case 1:
					if (string.IsNullOrWhiteSpace(model.UserName))
					{
						ModelState.AddModelError(string.Empty, "会员名称不能为空");
						return View(model);
					}
					bFlag = await _UsersService.UpdateAsync("GroupID=@GroupID", " and UserName in @UserName", new { UserName = StringHelper.GetArrayBySplit<string>(model.UserName).ToArray(), GroupID = model.RightGroupID });
					break;
				case 2:
					if (string.IsNullOrWhiteSpace(model.GroupIDs))
					{
						ModelState.AddModelError(string.Empty, "会员组不能为空");
						return View(model);
					}
					bFlag = await _UsersService.UpdateAsync("GroupID=@GroupID", " and GroupID in @GroupIDs", new { GroupIDs = StringHelper.GetArrayBySplit<int>(model.GroupIDs).ToArray(), GroupID = model.RightGroupID });
					break;
			}
			if (bFlag)
			{
				Utility.WriteMessage("移动成功", "mRefresh");
			}
			else
			{
				Utility.WriteMessage("移动失败", "mClose");
			}
			return Content(string.Empty);
		}
		#endregion

		#region 会员激励
		/// <summary>
		/// 会员激励
		/// </summary>
		/// <param name="ids"></param>
		/// <param name="idType"></param>
		/// <param name="eType"></param>
		/// <param name="eAction"></param>
		/// <returns></returns>
		[AdminAuthorize(Roles = "SuperAdmin,UserMoneyManage,UserExpManage,UserPointManage,UserValidDateManage")]
		public async Task<IActionResult> EncourageStrategy(string ids, int idType = 1,int eType=0,string eAction = "Add")
		{
			var result = await _UserGroupsService.GetListAsync(p => true);
			EncourageStrategyViewModel encourageStrategyViewModel = new EncourageStrategyViewModel();
			encourageStrategyViewModel.eType = eType;
			encourageStrategyViewModel.eAction = eAction;
			encourageStrategyViewModel.IdType = idType;
			switch (idType)
			{
				case 1:
					encourageStrategyViewModel.ids = ids;
					break;
				case 2:
					encourageStrategyViewModel.UserName = ids;
					break;
				case 3:
					encourageStrategyViewModel.GroupIDs = ids;
					break;
			}
			
			return View(encourageStrategyViewModel);
		}
		/// <summary>
		/// 会员激励
		/// </summary>
		/// <param name="model"></param>
		/// <param name="collection"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,UserMoneyManage,UserExpManage,UserPointManage,UserValidDateManage")]
		public async Task<ActionResult> EncourageStrategy(EncourageStrategyViewModel model = null, IFormCollection collection = null)
		{
			string ids = string.Empty;
			switch (model.IdType)
			{
				case 1:
					ids = model.ids;
					break;
				case 2:
					ids = model.UserName;
					break;
				case 3:
					ids = model.GroupIDs;
					break;
			}
			bool bFlag = await _UsersService.UserEncourageStrategyAsync(model.eType, model.eAction, model.IdType, ids, model.HowMany, model.Remark, model.Memo);
			if (bFlag)
			{
				Utility.WriteMessage("操作成功", "mRefresh");
			}
			else
			{
				Utility.WriteMessage("操作失败", "mClose");
			}
			return Content(string.Empty);
		}
		#endregion

		#region 修改会员权限
		/// <summary>
		/// 显示修改会员权限页面
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		[AdminAuthorize(Roles = "SuperAdmin,UserModifyPermissions")]
		public async Task<IActionResult> UserModifyPermissions(int id)
		{
			var model = new UsersEntity();
			model.UserID = id;
			if (id <= 0)
			{
				Utility.WriteMessage("会员不存在", "mClose");
				return Content(string.Empty);
			}
			model = await _UsersService.GetAsync(p => p.UserID == id);
			if (model == null || model.UserID <= 0)
			{
				Utility.WriteMessage("会员不存在", "mClose");
				return Content(string.Empty);
			}
			return View(model);
		}

		/// <summary>
		/// 修改会员权限
		/// </summary>
		/// <param name="id"></param>
		/// <param name="model"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,UserModifyPermissions")]
		public async Task<IActionResult> UserModifyPermissions(int id = 0, UsersEntity model = null)
		{
			if (model.UserID <= 0)
			{
				Utility.WriteMessage("会员不存在", "mClose");
				return Content(string.Empty);
			}
			if(model.IsInheritGroupRole)//继承自会员组权限
			{
				var oldModel = _UsersService.Get(p => p.UserID == model.UserID);
				oldModel.IsInheritGroupRole = model.IsInheritGroupRole;
				if (await _UsersService.UpdateAsync(oldModel))
				{
					Utility.WriteMessage("修改成功", "mRefresh");
				}
				else
				{
					Utility.WriteMessage("修改失败", "mClose");
				}
				return Content(string.Empty);
			}
			else//单独设置权限
			{
				return RedirectToAction("UserGroupPermissions", new { id = model.UserID, IdType = 0 });
			}
		}
		#endregion

		#region 会员编辑
		/// <summary>
		/// 会员编辑
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		[AdminAuthorize(Roles = "SuperAdmin,UserAdd,UserModify")]
		public IActionResult UserEdit(int id = 0)
		{
			//学历
			var EducationList = _DictionaryServiceApp.GetDictionaryFieldValue("Contacter","Education");
			EducationList.Insert(0, new DictionaryValue { DataTextField = "请选择", DataValueField = -1,IsDefault=true });
			var selectList = new SelectList(EducationList, "DataValueField", "DataTextField");
			var selectItemList = new List<SelectListItem>();
			selectItemList.AddRange(selectList);
			ViewBag.EducationList = selectItemList;
			//月收入
			var IncomeList = _DictionaryServiceApp.GetDictionaryFieldValue("Contacter", "Income");
			IncomeList.Insert(0, new DictionaryValue { DataTextField = "请选择", DataValueField = -1, IsDefault = true });
			var selectListIncome = new SelectList(IncomeList, "DataValueField", "DataTextField");
			var selectItemListIncome = new List<SelectListItem>();
			selectItemListIncome.AddRange(selectListIncome);
			ViewBag.IncomeList = selectItemListIncome;

			//联系人扩展字段列表
			IList<FieldInfo> contacterOptionFieldList = _ModelsService.GetFieldListByModelType(ModelType.UserOption,false);
			if (contacterOptionFieldList == null)
			{
				contacterOptionFieldList = new List<FieldInfo>();
			}
			
			var model = new UserViewModel();
			model.id = id;
			model.Action = Utility.Query("Action");
			if (id <= 0)
			{
				model.Users = new UsersEntity();
				model.Contacter = new ContacterEntity();
				model.ContacterOption = new DataTable();
				model.ContacterOptionFieldList = contacterOptionFieldList;
				return View(model);
			}
			//会员
			UsersEntity usersEntity = _UsersService.Get(p => p.UserID == id);
			if(usersEntity == null)
			{
				usersEntity = new UsersEntity();
			}
			//联系人
			ContacterEntity contacterEntity = _ContacterService.Get(p => p.UserName == usersEntity.UserName);
			if (contacterEntity == null)
			{
				contacterEntity = new ContacterEntity();
			}
			//联系人扩展数据
			DataTable dtContacterOption = _ContacterService.GetDataOption((int)contacterEntity.ContacterID);
			
			model.Users = usersEntity;
			model.Contacter = contacterEntity;
			model.EmergencyContactList = contacterEntity.EmergencyContactList;
			model.FamilyEntity = contacterEntity.FamilyEntity;
			model.ContacterOption = dtContacterOption;
			model.ContacterOptionFieldList = contacterOptionFieldList;
			if(usersEntity.UserType == (int)UserTypeEnum.Creator)
			{
				//商户
				var companyEntity = _CompanyService.Get(p => p.CompanyID == usersEntity.CompanyID);
				if (companyEntity == null)
				{
					companyEntity = new CompanyEntity();
				}
				//商户扩展数据
				DataTable dtCompanyOption = _CompanyService.GetDataOption((int)companyEntity.CompanyID);
				//商户扩展字段列表
				IList<FieldInfo> companyOptionFieldList = _ModelsService.GetFieldListByModelType(ModelType.CompanyOption, false);
				if (companyOptionFieldList == null)
				{
					companyOptionFieldList = new List<FieldInfo>();
				}
				model.ShowCompany = true;
				model.Company = companyEntity;
				model.CompanyOption = dtCompanyOption;
				model.CompanyOptionFieldList = companyOptionFieldList;
				
			}
			return View(model);
		}
		/// <summary>
		/// 会员编辑
		/// </summary>
		/// <param name="id"></param>
		/// <param name="model"></param>
		/// <param name="form"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,UserAdd,UserModify")]
		public async Task<ActionResult> UserEdit(int id = 0, UserViewModel model = null, IFormCollection form = null)
		{
			if (model.Users.GroupID != -2 && model.Users.GroupID <= 0)
			{
				Utility.WriteMessage("会员组不能为空", "mClose");
				return View(model);
			}
			if (string.IsNullOrWhiteSpace(model.Users.UserName))
			{
				Utility.WriteMessage("会员名称不能为空", "mClose");
				return View(model);
			}
			//联系人扩展字段列表
			IList<FieldInfo> contacterOptionFieldList = _ModelsService.GetFieldListByModelType(ModelType.UserOption,false);
			if (contacterOptionFieldList == null)
			{
				contacterOptionFieldList = new List<FieldInfo>();
			}
			if (id <= 0)
			{
				#region 添加
				#region 会员表信息
				if (string.IsNullOrWhiteSpace(model.Users.UserPassword))
				{
					Utility.WriteMessage("密码不能为空", "mClose");
					return View(model);
				}
				model.Users.UserName = DataSecurity.FilterSqlKeyword(model.Users.UserName);
				if (_UsersService.IsExist(p=>p.UserName == model.Users.UserName))
				{
					Utility.WriteMessage("会员名已经存在", "mClose");
					return View(model);
				}
				model.Users.UserPassword = StringHelper.MD5(model.Users.UserPassword);
				model.Users.UserFace = form["ctlUserFacehidFileUploadData"]; 
				model.Users.JoinTime = DateTime.Now;
				model.Users.RegTime = DateTime.Now;
				model.Users.UserStatus = (int)UserStatusEnum.None;
				model.Users.IsInheritGroupRole = true;
				model.Users.UserType = (int)UserTypeEnum.Persional;
				model.Users.UserCultureName = "zh-CN";
				model.Users.PrivacySetting = 0;
				if (!string.IsNullOrEmpty(model.Users.Answer))
				{
					model.Users.Answer = StringHelper.MD5(model.Users.Answer);
				}
				model.Users.TrueName = model.Contacter.TrueName;
				model.Users.Mobile = model.Contacter.Mobile;
				model.Users.Email = model.Contacter.Email;
				model.Users.Sex = model.Contacter.Sex;
				#endregion
				#region 联系人表信息
				model.Contacter.ContacterID = 0;
				model.Contacter.UserName = model.Users.UserName;
				model.Contacter.Province = form["ctlContacterProvince"];
				model.Contacter.City = form["ctlContacterCity"];
				model.Contacter.Area = form["ctlContacterArea"];
				model.Contacter.IDCardPic = form["ctlIDCardPichidFileUploadData"];
				model.Contacter.IDCardProvince = form["ctlIDCardRegionProvince"];
				model.Contacter.IDCardCity = form["ctlIDCardRegionCity"];
				model.Contacter.IDCardArea = form["ctlIDCardRegionArea"];
				model.Contacter.BankCardPic = form["ctlBankCardPichidFileUploadData"];
				model.Contacter.EmergencyContact = model.EmergencyContactList.ToJson();
				model.Contacter.Family = model.FamilyEntity.ToJson();
				model.Contacter.UserType = (int)ContacterType.Persional;
				model.Contacter.UpdateTime = DateTime.Now;
				model.Contacter.CreateTime = DateTime.Now;
				model.Contacter.ClientID = 0;
				model.Contacter.ParentID = 0;
				model.Contacter.Owner = "";
				DataTable dtContacterOption = Utility.GetDataOptionByForm(form, contacterOptionFieldList, "Contacter");
				model.Contacter.Fields = dtContacterOption;
				#endregion
				if(!await _UsersService.AddUserFullAsync(model.Users, model.Contacter))
				{
					Utility.WriteMessage("添加失败", "mClose");
					return View(model);
				}
				id = model.Users.UserID.ToInt32();
				string Action = Utility.Request("Action");
				if (string.Compare(Action, "AddToCompany", StringComparison.OrdinalIgnoreCase) == 0)
				{
					return RedirectToAction("RegCompany", new { UserID=id });
				}
				#endregion
			}
			else
			{
				#region 修改
				#region 会员表信息
				UsersEntity usersEntity = _UsersService.Get(p => p.UserID == id);
				Utility.SaveForm(form, usersEntity, "Users.");
				if (!string.IsNullOrWhiteSpace(model.Users.UserPassword))
				{
					usersEntity.UserPassword = StringHelper.MD5(model.Users.UserPassword);
				}
				usersEntity.UserFace = form["ctlUserFacehidFileUploadData"];
				#endregion
				#region 联系人表信息
				ContacterEntity contacterEntity = _ContacterService.Get(p => p.UserName == usersEntity.UserName);
				Utility.SaveForm(form, contacterEntity, "Contacter.");
				contacterEntity.Province = form["ctlContacterProvince"];
				contacterEntity.City = form["ctlContacterCity"];
				contacterEntity.Area = form["ctlContacterArea"];
				contacterEntity.IDCardPic = form["ctlIDCardPichidFileUploadData"];
				contacterEntity.IDCardProvince = form["ctlIDCardRegionProvince"];
				contacterEntity.IDCardCity = form["ctlIDCardRegionCity"];
				contacterEntity.IDCardArea = form["ctlIDCardRegionArea"];
				contacterEntity.BankCardPic = form["ctlBankCardPichidFileUploadData"];
				contacterEntity.EmergencyContact = model.EmergencyContactList.ToJson();
				contacterEntity.Family = model.FamilyEntity.ToJson();
				contacterEntity.UpdateTime = DateTime.Now;
				DataTable dtContacterOption = Utility.GetDataOptionByForm(form, contacterOptionFieldList, "Contacter");
				contacterEntity.Fields = dtContacterOption;

				usersEntity.TrueName = contacterEntity.TrueName;
				usersEntity.Mobile = contacterEntity.Mobile;
				usersEntity.Email = contacterEntity.Email;
				usersEntity.Sex = contacterEntity.Sex;
				#endregion
				if (!await _UsersService.UpdateUserFullAsync(usersEntity, contacterEntity))
				{
					Utility.WriteMessage("修改失败", "mClose");
					return View(model);
				}
				if (usersEntity.UserType == (int)UserTypeEnum.Creator)
				{
					var companyEntity = _CompanyService.Get(usersEntity.CompanyID);
					Utility.SaveForm(form, companyEntity,"Company.");
					companyEntity.CompanyPic = form["ctlCompanyPichidFileUploadData"];
					//companyEntity.Province = form["ctlCompanyRegionProvince"];
					//companyEntity.City = form["ctlCompanyRegionCity"];
					//companyEntity.Area = form["ctlCompanyRegionArea"];
					//商户扩展字段列表
					IList<FieldInfo> companyOptionFieldList = _ModelsService.GetFieldListByModelType(ModelType.CompanyOption, false);
					if (companyOptionFieldList == null)
					{
						companyOptionFieldList = new List<FieldInfo>();
					}
					companyEntity.Fields = Utility.GetDataOptionByForm(form, companyOptionFieldList, "Company");
					//更新公司信息
					await _CompanyService.UpdateFullAsync(companyEntity);
				}
				#endregion
			}
			Utility.WriteMessage("编辑成功", "mRefresh");
			return View(model);
		}
		#endregion

		#region 查看会员
		/// <summary>
		/// 查看会员
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		[AdminAuthorize(Roles = "SuperAdmin,UserView")]
		public IActionResult ViewUser(int id = 0)
		{
			if (id <= 0)
			{
				Utility.WriteErrMsg("会员不存在");
				return View();
			}
			//会员
			UsersEntity usersEntity = _UsersService.Get(p => p.UserID == id);
			if (usersEntity == null)
			{
				Utility.WriteErrMsg("会员不存在");
				return View();
			}
			//会员组
			var userGroupsEntity = _UserGroupsService.Get(usersEntity.GroupID);
			if (userGroupsEntity == null)
			{
				Utility.WriteErrMsg("会员所属的会员组不存在");
				return View();
			}
			//联系人
			ContacterEntity contacterEntity = _ContacterService.Get(p => p.UserName == usersEntity.UserName);
			if (contacterEntity == null)
			{
				Utility.WriteErrMsg("会员不存在");
				return View();
			}
			//联系人扩展数据
			DataTable dtContacterOption = _ContacterService.GetDataOption((int)contacterEntity.ContacterID);
			//联系人扩展字段列表
			IList<FieldInfo> contacterOptionFieldList = _ModelsService.GetFieldListByModelType(ModelType.UserOption, false);
			if (contacterOptionFieldList == null)
			{
				contacterOptionFieldList = new List<FieldInfo>();
			}

			//学历
			ViewBag.Education = _DictionaryServiceApp.GetDictionaryFieldValue("Contacter", "Education")[contacterEntity.Education.ToInt32()].DataTextField;
			//月收入
			ViewBag.Income = _DictionaryServiceApp.GetDictionaryFieldValue("Contacter", "Income")[contacterEntity.Income.ToInt32()].DataTextField;

			var model = new UserViewModel();
			model.id = id;
			model.Action = Utility.Query("Action");
			model.GroupName = userGroupsEntity.GroupName;
			model.Users = usersEntity;
			model.Contacter = contacterEntity;
			model.EmergencyContactList = contacterEntity.EmergencyContactList;
			model.FamilyEntity = contacterEntity.FamilyEntity;
			model.ContacterOption = dtContacterOption;
			model.ContacterOptionFieldList = contacterOptionFieldList;
			if (usersEntity.UserType == (int)UserTypeEnum.Creator)
			{
				//商户
				var companyEntity = _CompanyService.Get(p => p.CompanyID == usersEntity.CompanyID);
				if (companyEntity == null)
				{
					companyEntity = new CompanyEntity();
				}
				//商户扩展数据
				DataTable dtCompanyOption = _CompanyService.GetDataOption((int)companyEntity.CompanyID);
				//商户扩展字段列表
				IList<FieldInfo> companyOptionFieldList = _ModelsService.GetFieldListByModelType(ModelType.CompanyOption, false);
				if (companyOptionFieldList == null)
				{
					companyOptionFieldList = new List<FieldInfo>();
				}
				//商户成员
				DataTable dtCompanyMemberInfo = _CompanyService.GetMemberInfo((int)companyEntity.CompanyID);

				model.ShowCompany = true;
				model.Company = companyEntity;
				model.CompanyOption = dtCompanyOption;
				model.CompanyOptionFieldList = companyOptionFieldList;
				model.CompanyMemberInfo = dtCompanyMemberInfo;
			}
			return View(model);
		}
		
		#endregion

		#region 进入会员中心
		/// <summary>
		/// 进入会员中心
		/// </summary>
		/// <param name="UserName"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,ChangeUser")]
		public async Task<IActionResult> EnterUserCenter(string UserName)
		{
			ResultInfo resultInfo = new ResultInfo();
			if (string.IsNullOrEmpty(UserName))
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "会员不存在";
				return Json(resultInfo);
			}
			//会员
			UsersEntity usersEntity = _UsersService.GetByUserName(UserName);
			if (usersEntity == null)
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "会员不存在";
				return Json(resultInfo);
			}
			var userPrincipal = _UsersService.CreateClaimsIdentity(usersEntity);
			await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
			{
				//ExpiresUtc = DateTime.UtcNow.AddMinutes(30),
				IsPersistent = false,
				AllowRefresh = false
			});
			resultInfo.Status = 1;
			resultInfo.Msg = "";
			return Json(resultInfo);
		}
		#endregion

		#region 会员组列表
		/// <summary>
		/// 显示会员组列表页面
		/// </summary>
		/// <returns></returns>
		[AdminAuthorize(Roles = "SuperAdmin,UserGroupManage")]
		public IActionResult UserGroupManage()
		{
			return View();
		}
		/// <summary>
		/// 得到会员组列表分页数据
		/// </summary>
		/// <returns></returns>
		[AdminAuthorize(Roles = "SuperAdmin,UserGroupManage")]
		public IActionResult GetUserGroupManage()
		{
			int PageNum = Utility.Query("PageNum", 1);
			int PageSize = Utility.Query("PageSize", 10);
			string filter = " 1=1 ";
			int RecordTotal;
			var result = _UserGroupsService.GetListPaged(startRowIndexId: (PageNum - 1) * PageSize, maxNumberRows: PageSize,
				StrColumn: string.Empty, TableName: string.Empty, Filter: filter,
				SortColumn: "GroupID", Sorts: "asc", out RecordTotal).ToList();
			_UserGroupsService.CountUserNumber(result);
			PagerModel<UserGroupsEntity> pagerModel = new PagerModel<UserGroupsEntity>(PageNum, PageSize, RecordTotal, result);
			return Json(pagerModel);
		}
		/// <summary>
		/// 得到会员组列表，不包括匿名会员组
		/// </summary>
		/// <returns></returns>
		public IActionResult GetUserGroupsList()
		{
			var list = _UserGroupsService.GetList(p => p.GroupID > 0);
			return Json(list);
		}
		/// <summary>
		/// 删除会员组
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,UserGroupManage")]
		public async Task<ActionResult> DelUserGroup(int id)
		{
			if (id <= 0)
			{
				return Json(new
				{
					Result = "删除失败！没有指定要删除的记录ID！"
				});
			}
			try
			{
				if (await _UserGroupsService.DeleteFullAsync(id))
				{
					return Json(new
					{
						Result = "ok"
					});
				}
				else
				{
					return Json(new
					{
						Result = "删除失败！会员组不存在或组中有会员！"
					});
				}
			}
			catch (Exception ex)
			{
				return Json(new
				{
					Result = "删除失败！" + ex.Message
				});
			}
		}
		#endregion

		#region 会员组编辑
		/// <summary>
		/// 会员组编辑
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		[AdminAuthorize(Roles = "SuperAdmin,UserGroupManage")]
		public IActionResult UserGroupEdit(int id = 0)
		{
			var model = new UserGroupsEntity();
			model.GroupID = id;
			if (id == -2)
			{
				Utility.WriteMessage("匿名用户组不能编辑", "mClose");
				return View(model);
			}
			if (id <= 0)
				return View(model);
			model = _UserGroupsService.Get(p => p.GroupID == id);
			if (model == null || model.GroupID <= 0)
				return View(model);
			return View(model);
		}
		/// <summary>
		/// 会员组编辑
		/// </summary>
		/// <param name="id"></param>
		/// <param name="model"></param>
		/// <param name="collection"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,UserGroupManage")]
		public async Task<ActionResult> UserGroupEdit(int id = 0, UserGroupsEntity model = null, IFormCollection collection = null)
		{
			if (model.GroupID == -2)
			{
				ModelState.AddModelError(string.Empty, "匿名会员组不能编辑");
				return View(model);
			}
			if (string.IsNullOrWhiteSpace(model.GroupName))
			{
				ModelState.AddModelError(string.Empty, "组名称不能为空");
				return View(model);
			}
			if (string.IsNullOrWhiteSpace(model.Description))
			{
				model.Description = string.Empty;
			}
			if (model.GroupID <= 0)
			{
				#region 添加
				if (_UserGroupsService.UserGroupIsExist(model.GroupName))
				{
					ModelState.AddModelError(string.Empty, "添加失败！会员组名称已经存在！");
					return View(model);
				}
				if (!await _UserGroupsService.AddAsync(model))
				{
					ModelState.AddModelError(string.Empty, "添加失败");
					return View(model);
				}
				id = (int)model.GroupID;
				#endregion
			}
			else
			{
				#region 修改
				var oldModel = _UserGroupsService.Get(p => p.GroupID == model.GroupID);
				if(oldModel.GroupName != model.GroupName)
				{
					if (_UserGroupsService.UserGroupIsExist(model.GroupName))
					{
						ModelState.AddModelError(string.Empty, "该会员组已经存在，请使用另一会员组名！");
						return View(model);
					}
				}
				oldModel.GroupName = model.GroupName;
				oldModel.Description = model.Description;
				oldModel.GroupType = model.GroupType;
				if (!await _UserGroupsService.UpdateAsync(oldModel))
				{
					ModelState.AddModelError(string.Empty, "修改失败");
					return View(model);
				}
				#endregion
			}
			return RedirectToAction("UserGroupPermissions", new { id = model.GroupID, groupName = model.GroupName });
		}
		#endregion

		#region 会员组-常规权限设置(菜单、字段)
		/// <summary>
		/// 会员组-常规权限设置
		/// </summary>
		/// <param name="id"></param>
		/// <param name="IdType"></param>
		/// <returns></returns>
		[AdminAuthorize(Roles = "SuperAdmin,UserGroupManage")]
		public async Task<ActionResult> UserGroupPermissions(int id = 0, int IdType = 1)
		{
			UserGroupsEntity userGroupsEntity = null;
			UsersEntity usersEntity = null;
			UserPurviewEntity userPurviewEntity = null;
			UserGroupPermissionsViewModels permissionsViewModels = new UserGroupPermissionsViewModels();
			if (IdType == 1)
			{
				if (id <= 0 && id != -2)
				{
					Utility.WriteMessage("权限配置必须指定会员组", "mClose");
					return View(permissionsViewModels);
				}
				userGroupsEntity = await _UserGroupsService.GetAsync(p => p.GroupID == id);
				if (userGroupsEntity == null)
				{
					Utility.WriteMessage("指定的会员组不存在", "mClose");
					return View(permissionsViewModels);
				}
				ViewBag.Name = userGroupsEntity.GroupName;
				userPurviewEntity = userGroupsEntity.UserGroupPurview;
			}
			else if (IdType == 0)
			{
				if (id <= 0)
				{
					Utility.WriteMessage("权限配置必须指定会员", "mClose");
					return View(permissionsViewModels);
				}
				usersEntity = await _UsersService.GetAsync(p => p.UserID == id);
				if (usersEntity == null)
				{
					Utility.WriteMessage("指定的会员不存在", "mClose");
					return View(permissionsViewModels);
				}
				ViewBag.Name = usersEntity.UserName;
				userPurviewEntity = usersEntity.UserPurview;
			}
			else
			{
				Utility.WriteMessage("权限类型没有指定", "mClose");
				return View(permissionsViewModels);
			}
			if (userPurviewEntity == null)
			{
				userPurviewEntity = new UserPurviewEntity();
			}
			ViewBag.ID = id;
			permissionsViewModels.IdType = IdType;
			permissionsViewModels.GroupPermissionsList = DataConverter.ToString(userPurviewEntity.AllCheckCode);
			permissionsViewModels.PurviewEntity = userPurviewEntity;
			//菜单权限
			string userMenuPath = Utility.GetUserMenuPath();
			XmlHelper xmlHelper = XmlHelper.Instance(FileHelper.MapPath(userMenuPath), XmlType.File);
			XmlDocument xmlDoc = xmlHelper.XmlDoc;
			XmlNode rootNode = xmlDoc.SelectSingleNode("menu");
			if (rootNode == null)
			{
				Utility.WriteMessage("菜单配置文件不存在menu根元素", "mClose");
				return View(permissionsViewModels);
			}
			if (rootNode.HasChildNodes)
			{
				IList<MenuEntity> menuEntityList = new List<MenuEntity>();
				foreach (XmlNode channelMenuNode in rootNode)
				{
					string operateCode = XmlHelper.GetAttributesValue(channelMenuNode, "operateCode");
					string NodeName = channelMenuNode.Name;
					string menuID = XmlHelper.GetAttributesValue(channelMenuNode, "id");
					string title = XmlHelper.GetAttributesValue(channelMenuNode, "title");
					string Description = XmlHelper.GetAttributesValue(channelMenuNode, "Description");
					string rightUrl = XmlHelper.GetAttributesValue(channelMenuNode, "rightUrl");
					string MenuType = XmlHelper.GetAttributesValue(channelMenuNode, "type");
					string MenuIcon = XmlHelper.GetAttributesValue(channelMenuNode, "icon");
					bool ShowOnForm = DataConverter.CBoolean(XmlHelper.GetAttributesValue(channelMenuNode, "ShowOnForm"));
					bool ShowOnMenu = DataConverter.CBoolean(XmlHelper.GetAttributesValue(channelMenuNode, "ShowOnMenu"));
					if (!ShowOnForm)
						continue;
					MenuEntity menuEntity = new MenuEntity
					{
						NodeName = NodeName,
						ID = menuID,
						Title = title,
						OperateCode = operateCode,
						Description = Description,
						Url = rightUrl,
						MenuType = MenuType,
						MenuIcon = MenuIcon,
						ShowOnForm = ShowOnForm,
						ShowOnMenu = ShowOnMenu
					};
					menuEntity.MenuItem = InitSubMenu(channelMenuNode);
					menuEntityList.Add(menuEntity);
				}
				permissionsViewModels.MenuEntityList = menuEntityList;
			}
			//字段权限
			var groupFieldPermissionsViewModelsList = new List<GroupFieldPermissionsViewModels>();
			var modelsEntityList = await _ModelsService.GetListAsync(p => p.IsDisabled == false);
			foreach (ModelsEntity modelsEntity in modelsEntityList)
			{
				var fieldInfoList = modelsEntity.Field.ToXmlObject<List<FieldInfo>>();
				fieldInfoList.Sort(new FieldInfoComparer());
				var vm = new GroupFieldPermissionsViewModels();
				vm.ModelsEntity = modelsEntity;
				vm.FieldInfoList = fieldInfoList;
				vm.GroupFieldPermissionsEntityList = await _UserGroupsService.GetFieldPermissionsById(id, (int)modelsEntity.ModelID, IdType);
				groupFieldPermissionsViewModelsList.Add(vm);
			}
			permissionsViewModels.GroupFieldPermissionsViewModelsList = groupFieldPermissionsViewModelsList;
			return View(permissionsViewModels);
		}
		/// <summary>
		/// 会员组-常规权限设置
		/// </summary>
		/// <param name="id"></param>
		/// <param name="IdType"></param>
		/// <param name="viewModel"></param>
		/// <param name="collection"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,UserGroupManage")]
		public async Task<ActionResult> UserGroupPermissions(int id, int IdType, UserGroupPermissionsViewModels viewModel, IFormCollection collection)
		{
			UserGroupsEntity userGroupsEntity = null;
			UsersEntity usersEntity = null;
			UserPurviewEntity userPurviewEntity = null;
			if (IdType == 1)
			{
				if (id <= 0 && id != -2)
				{
					Utility.WriteMessage("权限配置必须指定会员组", "mClose");
					return Content(string.Empty);
				}
				userGroupsEntity = await _UserGroupsService.GetAsync(p => p.GroupID == id);
				if (userGroupsEntity == null)
				{
					Utility.WriteMessage("指定的会员组不存在", "mClose");
					return Content(string.Empty);
				}
				userPurviewEntity = userGroupsEntity.UserGroupPurview;
			}
			else if (IdType == 0)
			{
				if (id <= 0)
				{
					Utility.WriteMessage("权限配置必须指定会员", "mClose");
					return Content(string.Empty);
				}
				usersEntity = await _UsersService.GetAsync(p => p.UserID == id);
				if (usersEntity == null)
				{
					Utility.WriteMessage("指定的会员不存在", "mClose");
					return Content(string.Empty);
				}
				userPurviewEntity = usersEntity.UserPurview;
			}
			else
			{
				Utility.WriteMessage("权限类型没有指定", "mClose");
				return Content(string.Empty);
			}

			//字段权限
			var ModelFieldPurview = collection["ModelFieldPurview"];
			await _UserGroupsService.DeleteFieldPermissionFromGroup(groupID:id,idType:IdType);
			await _UserGroupsService.AddFieldPermissionToUserGroup(id, OperateCode.ContentFieldInput, ModelFieldPurview, IdType);

			if (userPurviewEntity == null)
			{
				userPurviewEntity = new UserPurviewEntity();
			}
			//菜单权限
			var ModelPurview = collection["ModelPurview"];
			userPurviewEntity.AllCheckCode = ModelPurview;
			//其他权限
			userPurviewEntity.EnableComment = viewModel.PurviewEntity.EnableComment;
			userPurviewEntity.CommentNeedCheck = viewModel.PurviewEntity.CommentNeedCheck;
			userPurviewEntity.EnableUpload = viewModel.PurviewEntity.EnableUpload;
			userPurviewEntity.UploadSize = viewModel.PurviewEntity.UploadSize;
			userPurviewEntity.Discount = viewModel.PurviewEntity.Discount;
			userPurviewEntity.Overdraft = viewModel.PurviewEntity.Overdraft;
			if (ConfigHelper.Get<UserConfig>().EnablePoint || ConfigHelper.Get<UserConfig>().EnableValidNum)
			{
				userPurviewEntity.ChargeType = viewModel.PurviewEntity.ChargeType;
			}
			if (ConfigHelper.Get<UserConfig>().EnablePoint)
			{
				userPurviewEntity.ChargePointType = viewModel.PurviewEntity.ChargePointType;
				userPurviewEntity.TotalViewInfoNumber = viewModel.PurviewEntity.TotalViewInfoNumber;
				userPurviewEntity.ViewInfoNumberOneDay = viewModel.PurviewEntity.ViewInfoNumberOneDay;
			}
			bool bFlag = false;
			if (userGroupsEntity != null)
			{
				userGroupsEntity.GroupSetting = userPurviewEntity.ToXml();
				bFlag = await _UserGroupsService.UpdateAsync(userGroupsEntity);
			}
			else if (usersEntity != null)
			{
				usersEntity.UserSetting = userPurviewEntity.ToXml();
				usersEntity.IsInheritGroupRole = false;
				bFlag = await _UsersService.UpdateAsync(usersEntity);
			}
			if (bFlag)
			{
				Utility.WriteMessage("设置权限成功", "mRefresh");
			}
			else
			{
				Utility.WriteMessage("设置权限失败", "mClose");
			}
			return Content(string.Empty);
		}
		#endregion

		#region 会员组-发布权限设置(节点、专题)
		/// <summary>
		/// 会员组-发布权限设置
		/// </summary>
		/// <param name="id"></param>
		/// <param name="IdType"></param>
		/// <returns></returns>
		[AdminAuthorize(Roles = "SuperAdmin,UserGroupManage")]
		public async Task<ActionResult> PublishPermissions(int id = 0,int IdType = 1)
		{
			UserGroupsEntity userGroupsEntity = null;
			UsersEntity usersEntity = null;
			var permissionsViewModels = new PublishPermissionsViewModel();
			if (IdType == 1)
			{
				if (id <= 0 && id != -2)
				{
					Utility.WriteMessage("权限配置必须指定会员组", "mClose");
					return View(permissionsViewModels);
				}
				userGroupsEntity = await _UserGroupsService.GetAsync(p => p.GroupID == id);
				if (userGroupsEntity == null)
				{
					Utility.WriteMessage("指定的会员组不存在", "mClose");
					return View(permissionsViewModels);
				}
				permissionsViewModels.PurviewEntity = userGroupsEntity.UserGroupPurview;
			}
			else if (IdType == 0)
			{
				if (id <= 0)
				{
					Utility.WriteMessage("权限配置必须指定会员", "mClose");
					return View(permissionsViewModels);
				}
				usersEntity = await _UsersService.GetAsync(p => p.UserID == id);
				if (usersEntity == null)
				{
					Utility.WriteMessage("指定的会员不存在", "mClose");
					return View(permissionsViewModels);
				}
				permissionsViewModels.PurviewEntity = usersEntity.UserPurview;
			}
			else
			{
				Utility.WriteMessage("权限类型没有指定", "mClose");
				return View(permissionsViewModels);
			}
			if (permissionsViewModels.PurviewEntity == null)
			{
				permissionsViewModels.PurviewEntity = new UserPurviewEntity();
			}
			ViewBag.ID = id;
			permissionsViewModels.IdType = IdType;
			permissionsViewModels.NodeList = _NodesService.GetNodeListByContainer();
			permissionsViewModels.GroupNodePermissionsList = await _UserGroupsService.GetNodePermissionsById(id,-3,OperateCode.None,IdType);
			return View(permissionsViewModels);
		}
		/// <summary>
		/// 会员组-发布权限设置
		/// </summary>
		/// <param name="id"></param>
		/// <param name="IdType"></param>
		/// <param name="viewModel"></param>
		/// <param name="collection"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,UserGroupManage")]
		public async Task<ActionResult> PublishPermissions(int id, int IdType, PublishPermissionsViewModel viewModel, IFormCollection collection = null)
		{
			UserGroupsEntity userGroupsEntity = null;
			UsersEntity usersEntity = null;
			UserPurviewEntity userPurviewEntity = null;
			if (IdType == 1)
			{
				if (id <= 0 && id != -2)
				{
					Utility.WriteMessage("权限配置必须指定会员组", "mClose");
					return Content(string.Empty);
				}
				userGroupsEntity = await _UserGroupsService.GetAsync(p => p.GroupID == id);
				if (userGroupsEntity == null)
				{
					Utility.WriteMessage("指定的会员组不存在", "mClose");
					return Content(string.Empty);
				}
				userPurviewEntity = userGroupsEntity.UserGroupPurview;
			}
			else if (IdType == 0)
			{
				if (id <= 0)
				{
					Utility.WriteMessage("权限配置必须指定会员", "mClose");
					return Content(string.Empty);
				}
				usersEntity = await _UsersService.GetAsync(p => p.UserID == id);
				if (usersEntity == null)
				{
					Utility.WriteMessage("指定的会员不存在", "mClose");
					return Content(string.Empty);
				}
				userPurviewEntity = usersEntity.UserPurview;
			}
			else
			{
				Utility.WriteMessage("权限类型没有指定", "mClose");
				return Content(string.Empty);
			}
			//保存节点权限设置
			await _UserGroupsService.DeleteNodePermissionFromGroupAsync(id, -3, OperateCode.NodeContentInput, IdType);
			await _UserGroupsService.DeleteNodePermissionFromGroupAsync(id, -3, OperateCode.NodeNoNeedCheck, IdType);
			await _UserGroupsService.DeleteNodePermissionFromGroupAsync(id, -3, OperateCode.NodeManageSelfInfo, IdType);
			var ModelPurview = collection["ModelPurview"];
			if (!string.IsNullOrEmpty(ModelPurview))
			{
				await _UserGroupsService.AddNodePermissionToUserGroup(id, ModelPurview, IdType);
			}
			//保存会员组（会员）权限设置
			if (userPurviewEntity == null)
			{
				userPurviewEntity = new UserPurviewEntity();
			}
			userPurviewEntity.SetEditor = viewModel.PurviewEntity.SetEditor;
			userPurviewEntity.MaxPublicInfoOneDay = viewModel.PurviewEntity.MaxPublicInfoOneDay;
			userPurviewEntity.MaxPublicInfo = viewModel.PurviewEntity.MaxPublicInfo;
			userPurviewEntity.IsXssFilter = viewModel.PurviewEntity.IsXssFilter;
			if (ConfigHelper.Get<UserConfig>().EnableExp)
			{
				userPurviewEntity.GetExp = viewModel.PurviewEntity.GetExp;
			}
			if (ConfigHelper.Get<UserConfig>().EnablePoint)
			{
				userPurviewEntity.GetPoint = viewModel.PurviewEntity.GetPoint;
			}
			bool bFlag = false;
			if (userGroupsEntity != null)
			{
				userGroupsEntity.GroupSetting = userPurviewEntity.ToXml();
				bFlag = await _UserGroupsService.UpdateAsync(userGroupsEntity);
			}
			else if (usersEntity != null)
			{
				usersEntity.UserSetting = userPurviewEntity.ToXml();
				bFlag = await _UsersService.UpdateAsync(usersEntity);
			}
			if (bFlag)
			{
				Utility.WriteMessage("设置权限成功", "mRefresh");
			}
			else
			{
				Utility.WriteMessage("设置权限失败", "mClose");
			}
			return Content(string.Empty);
		}
		#endregion

		#region 会员组-前台权限设置(节点)
		/// <summary>
		/// 会员组-前台权限设置
		/// </summary>
		/// <param name="id"></param>
		/// <param name="IdType"></param>
		/// <returns></returns>
		[AdminAuthorize(Roles = "SuperAdmin,UserGroupManage")]
		public async Task<ActionResult> UserGroupFrontPermissions(int id = 0, int IdType = 1)
		{
			UserGroupsEntity userGroupsEntity = null;
			UsersEntity usersEntity = null;
			var permissionsViewModels = new PublishPermissionsViewModel();
			if (IdType == 1)
			{
				if (id <= 0 && id != -2)
				{
					Utility.WriteMessage("权限配置必须指定会员组", "mClose");
					return View(permissionsViewModels);
				}
				userGroupsEntity = await _UserGroupsService.GetAsync(p => p.GroupID == id);
				if (userGroupsEntity == null)
				{
					Utility.WriteMessage("指定的会员组不存在", "mClose");
					return View(permissionsViewModels);
				}
				permissionsViewModels.PurviewEntity = userGroupsEntity.UserGroupPurview;
			}
			else if (IdType == 0)
			{
				if (id <= 0)
				{
					Utility.WriteMessage("权限配置必须指定会员", "mClose");
					return View(permissionsViewModels);
				}
				usersEntity = await _UsersService.GetAsync(p => p.UserID == id);
				if (usersEntity == null)
				{
					Utility.WriteMessage("指定的会员不存在", "mClose");
					return View(permissionsViewModels);
				}
				permissionsViewModels.PurviewEntity = usersEntity.UserPurview;
			}
			else
			{
				Utility.WriteMessage("权限类型没有指定", "mClose");
				return View(permissionsViewModels);
			}
			if (permissionsViewModels.PurviewEntity == null)
			{
				permissionsViewModels.PurviewEntity = new UserPurviewEntity();
			}
			var nodeList = new List<NodesEntity>();
			var nodeListTemp = _NodesService.GetNodeListByContainer();
			foreach (var item in nodeListTemp)
			{
				string BeginTag = _NodesService.GetTreeLine((int)item.Depth, item.ParentPath, (int)item.NextID, (int)item.Child);
				string EndTag = _NodesService.GetNodeDir((int)item.Child, (NodeType)item.NodeType, item.NodeDir);
				if (item.NodeName == "所有栏目")
				{
					BeginTag = BeginTag + "<span style='color:red'>";
					EndTag = "</span>" + EndTag;
				}
				else
				{
					//根据父节点的栏目权限和当前节点的栏目权限，确定当前节点的栏目权限
					int purviewType = 0;
					if (item.ParentID > 0)
					{
						purviewType = (int)_NodesService.GetCacheNodeById((int)item.ParentID).PurviewType;
					}
					if (purviewType < item.PurviewType)
					{
						purviewType = (int)item.PurviewType;
					}
					item.PurviewType = purviewType;
				}
				item.NodeName = BeginTag + item.NodeName + EndTag;
				nodeList.Add(item);
			}
			ViewBag.ID = id;
			permissionsViewModels.IdType = IdType;
			permissionsViewModels.NodeList = nodeList;
			permissionsViewModels.GroupNodePermissionsList = await _UserGroupsService.GetNodePermissionsById(id, -3, OperateCode.None, IdType);
			return View(permissionsViewModels);
		}
		/// <summary>
		/// 会员组-前台权限设置
		/// </summary>
		/// <param name="id"></param>
		/// <param name="IdType"></param>
		/// <param name="collection"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,UserGroupManage")]
		public async Task<ActionResult> UserGroupFrontPermissions(int id, int IdType, IFormCollection collection = null)
		{
			if (IdType == 1)
			{
				if (id <= 0 && id != -2)
				{
					Utility.WriteMessage("权限配置必须指定会员组", "mClose");
					return Content(string.Empty);
				}
			}
			else if (IdType == 0)
			{
				if (id <= 0)
				{
					Utility.WriteMessage("权限配置必须指定会员", "mClose");
					return Content(string.Empty);
				}
			}
			else
			{
				Utility.WriteMessage("权限类型没有指定", "mClose");
				return Content(string.Empty);
			}
			//保存节点权限设置
			bool bFlag = true;
			await _UserGroupsService.DeleteNodePermissionFromGroupAsync(id, -3, OperateCode.NodeContentSkim, IdType);
			await _UserGroupsService.DeleteNodePermissionFromGroupAsync(id, -3, OperateCode.NodeContentPreview, IdType);
			var ModelPurview = collection["ModelPurview"];
			if (!string.IsNullOrEmpty(ModelPurview))
			{
				bFlag = await _UserGroupsService.AddNodePermissionToUserGroup(id, ModelPurview, IdType);
			}
			if (bFlag)
			{
				Utility.WriteMessage("设置权限成功", "mRefresh");
			}
			else
			{
				Utility.WriteMessage("设置权限失败", "mClose");
			}
			return Content(string.Empty);
		}
		#endregion

		#region 商户列表
		/// <summary>
		/// 商户列表页面
		/// </summary>
		/// <returns></returns>
		[AdminAuthorize(Roles = "SuperAdmin,CompanyManage")]
		public ActionResult CompanyManage()
		{
			return View();
		}
		/// <summary>
		/// 得到商户列表的分页数据
		/// </summary>
		/// <returns></returns>
		[AdminAuthorize(Roles = "SuperAdmin,CompanyManage")]
		public IActionResult GetCompanyList()
		{
			int PageNum = Utility.Query("PageNum", 1);
			int PageSize = Utility.Query("PageSize", 10);
			string SearchName = Utility.Query("SearchName");
			string SearchKeyword = Utility.Query("SearchKeyword");
			int TabStatus = Utility.Query("TabStatus", 0);
			string filter = " 1=1 ";
			if (!string.IsNullOrEmpty(SearchKeyword))
			{
				filter += " and " + SearchName + " like '%" + DataSecurity.FilterBadChar(SearchKeyword) + "%'";
			}
			string strColumn = " C.*,(select UserName from Users U where U.CompanyID=C.CompanyID and U.UserType=1) as UserName ";
			string TableName = " Company C ";
			int RecordTotal;
			var result = _CompanyService.GetListPaged<dynamic>(startRowIndexId: (PageNum - 1) * PageSize, maxNumberRows: PageSize,
				StrColumn: strColumn, TableName: TableName, Filter: filter,
				SortColumn: "C.CompanyID", Sorts: "desc", out RecordTotal).ToList();
			var pagerModel = new PagerModel<dynamic>(PageNum, PageSize, RecordTotal, result);
			return Json(pagerModel);
		}
		/// <summary>
		/// 删除商户
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,CompanyManage")]
		public IActionResult DelCompany(int id)
		{
			if (id <= 0)
			{
				return Json(new
				{
					Result = "删除失败！没有指定要删除的记录ID！"
				});
			}
			try
			{
				if (_CompanyService.DeleteFull(id))
				{
					return Json(new
					{
						Result = "ok"
					});
				}
				else
				{
					return Json(new
					{
						Result = "删除失败！"
					});
				}
			}
			catch (Exception ex)
			{
				return Json(new
				{
					Result = "删除失败！" + ex.Message
				});
			}
		}
		/// <summary>
		/// 批量删除商户
		/// </summary>
		/// <param name="ids"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,CompanyManage")]
		public IActionResult DelCompanyMulti(string ids)
		{
			if (string.IsNullOrEmpty(ids))
			{
				return Json(new
				{
					Result = "删除失败！没有指定要删除的记录ID！"
				});
			}
			try
			{
				_CompanyService.DeleteFull(ids);
				return Json(new
				{
					Result = "ok"
				});
			}
			catch (Exception ex)
			{
				return Json(new
				{
					Result = "删除失败！" + ex.Message
				});
			}
		}
		#endregion

		#region 商户注册与编辑
		/// <summary>
		/// 商户注册
		/// </summary>
		/// <param name="UserID"></param>
		/// <returns></returns>
		[AdminAuthorize(Roles = "SuperAdmin,CompanyManage")]
		public IActionResult RegCompany(int UserID)
		{
			if(UserID <= 0)
			{
				Utility.WriteMessage("会员不存在", "mClose");
				return View();
			}
			RegCompanyViewModel regCompanyViewModel = new RegCompanyViewModel();
			regCompanyViewModel.CompanyList = _CompanyService.GetList().ToList();
			if(regCompanyViewModel.CompanyList == null)
			{
				regCompanyViewModel.CompanyList = new List<CompanyEntity>();
			}
			regCompanyViewModel.UserID = UserID;
			
			return View(regCompanyViewModel);
		}
		/// <summary>
		/// 商户注册
		/// </summary>
		/// <param name="UserID"></param>
		/// <param name="form"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,CompanyManage")]
		public async Task<ActionResult> RegCompany(int UserID, IFormCollection form = null)
		{
			if (UserID <= 0)
			{
				Utility.WriteMessage("会员不存在", "mClose");
				return View();
			}
			var companyEntity = new CompanyEntity();
			Utility.SaveForm(form, companyEntity, "Company.");
			companyEntity.CompanyPic = form["ctlCompanyPichidFileUploadData"];
			//商户扩展字段列表
			IList<FieldInfo> companyOptionFieldList = _ModelsService.GetFieldListByModelType(ModelType.CompanyOption, false);
			if (companyOptionFieldList == null)
			{
				companyOptionFieldList = new List<FieldInfo>();
			}
			companyEntity.Fields = Utility.GetDataOptionByForm(form, companyOptionFieldList, "Company");
			//添加公司
			if (await _CompanyService.AddFullAsync(companyEntity))
			{
				_UsersService.UpdateForCompany(companyEntity.CompanyID.ToInt32(), UserID, (int)UserTypeEnum.Creator, 0);
				Utility.WriteMessage("新建商户成功", "mRefresh");
				return View();
			}
			else
			{
				Utility.WriteMessage("新建商户失败", "mClose");
				return View();
			}
		}

		/// <summary>
		/// 加入商户
		/// </summary>
		/// <param name="UserID"></param>
		/// <param name="model"></param>
		/// <param name="form"></param>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,CompanyManage")]
		public void AppendCompany(int UserID, RegCompanyViewModel model, IFormCollection form = null)
		{
			string returnUrl = "/Admin/User/RegCompany?UserID=" + UserID;
			if (UserID <= 0)
			{
				Utility.WriteMessage("会员不存在", "mClose");
				return;
			}
			if (model.AppendCompanyID <= 0)
			{
				Utility.WriteMessage("找不到要加入的商户", returnUrl);
				return;
			}
			var companyEntity = _CompanyService.Get(model.AppendCompanyID);
			if (companyEntity == null)
			{
				Utility.WriteMessage("找不到要加入的商户", returnUrl);
				return;
			}
			if(_UsersService.UpdateForCompany(model.AppendCompanyID, UserID,model.UserType, companyEntity.ClientID.ToInt32()))
			{
				Utility.WriteMessage("加入商户成功", "mRefresh");
				return;
			}
			else
			{
				Utility.WriteMessage("加入商户失败", returnUrl);
				return;
			}
		}

		/// <summary>
		/// 商户编辑页面
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		[AdminAuthorize(Roles = "SuperAdmin,CompanyManage")]
		public IActionResult CompanyEdit(int id)
		{
			var model = new JXWebSite.Areas.Admin.Components.CompanyViewModel();
			//商户
			var companyEntity = _CompanyService.Get(p => p.CompanyID == id);
			if (companyEntity == null)
			{
				Utility.WriteMessage("商户不存在", "mClose");
				return View(model);
			}
			//商户扩展数据
			DataTable dtCompanyOption = _CompanyService.GetDataOption((int)companyEntity.CompanyID);
			//商户扩展字段列表
			IList<FieldInfo> companyOptionFieldList = _ModelsService.GetFieldListByModelType(ModelType.CompanyOption, false);
			if (companyOptionFieldList == null)
			{
				companyOptionFieldList = new List<FieldInfo>();
			}
			model.Company = companyEntity;
			model.CompanyOption = dtCompanyOption;
			model.CompanyOptionFieldList = companyOptionFieldList;
			return View(model);
		}
		/// <summary>
		/// 商户编辑
		/// </summary>
		/// <param name="id"></param>
		/// <param name="model"></param>
		/// <param name="form"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,CompanyManage")]
		public async Task<ActionResult> CompanyEdit(int id, JXWebSite.Areas.Admin.Components.CompanyViewModel model = null, IFormCollection form = null)
		{
			if (id <= 0)
			{
				Utility.WriteMessage("商户不存在", "mClose");
				return View(model);
			}
			else
			{
				#region 修改
				var companyEntity = _CompanyService.Get(id);
				Utility.SaveForm(form, companyEntity, "Company.");
				companyEntity.CompanyPic = form["ctlCompanyPichidFileUploadData"];
				//companyEntity.Province = form["ctlCompanyRegionProvince"];
				//companyEntity.City = form["ctlCompanyRegionCity"];
				//companyEntity.Area = form["ctlCompanyRegionArea"];
				//商户扩展字段列表
				IList<FieldInfo> companyOptionFieldList = _ModelsService.GetFieldListByModelType(ModelType.CompanyOption, false);
				if (companyOptionFieldList == null)
				{
					companyOptionFieldList = new List<FieldInfo>();
				}
				companyEntity.Fields = Utility.GetDataOptionByForm(form, companyOptionFieldList, "Company");
				//更新公司信息
				if(await _CompanyService.UpdateFullAsync(companyEntity))
				{
					Utility.WriteMessage("编辑成功", "mRefresh");
					return View(model);
				}
				else
				{
					Utility.WriteMessage("修改失败", "mClose");
					return View(model);
				}
				#endregion
			}
		}
		#endregion

		#region 商户查看
		/// <summary>
		/// 商户查看
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		[AdminAuthorize(Roles = "SuperAdmin,CompanyManage")]
		public IActionResult ViewCompany(int id = 0)
		{
			if (id <= 0)
			{
				Utility.WriteErrMsg("商户不存在");
				return View();
			}
			//商户
			var companyEntity = _CompanyService.Get(p => p.CompanyID == id);
			if (companyEntity == null)
			{
				companyEntity = new CompanyEntity();
			}
			//商户扩展数据
			DataTable dtCompanyOption = _CompanyService.GetDataOption((int)companyEntity.CompanyID);
			//商户扩展字段列表
			IList<FieldInfo> companyOptionFieldList = _ModelsService.GetFieldListByModelType(ModelType.CompanyOption, false);
			if (companyOptionFieldList == null)
			{
				companyOptionFieldList = new List<FieldInfo>();
			}
			//商户成员
			DataTable dtCompanyMemberInfo = _CompanyService.GetMemberInfo((int)companyEntity.CompanyID);

			var model = new JXWebSite.Areas.Admin.Components.CompanyViewModel();
			model.Company = companyEntity;
			model.CompanyOption = dtCompanyOption;
			model.CompanyOptionFieldList = companyOptionFieldList;
			model.CompanyMemberInfo = dtCompanyMemberInfo;
			return View(model);
		}
		#endregion

		#region 商户成员管理
		/// <summary>
		/// 从商户中移除
		/// </summary>
		/// <param name="UserName"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,CompanyManage")]
		public IActionResult RemoveFromCompany(string UserName)
		{
			if (string.IsNullOrEmpty(UserName))
			{
				return Json(new
				{
					Result = "移除失败！没有指定要移除的会员！"
				});
			}
			try
			{
				if (_UsersService.RemoveFromCompany(UserName))
				{
					return Json(new
					{
						Result = "ok"
					});
				}
				else
				{
					return Json(new
					{
						Result = "移除失败！"
					});
				}
			}
			catch (Exception ex)
			{
				return Json(new
				{
					Result = "移除失败！" + ex.Message
				});
			}
		}
		/// <summary>
		/// 升级为管理员
		/// </summary>
		/// <param name="UserName"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,CompanyManage")]
		public IActionResult AddToCompanyAdmin(string UserName)
		{
			if (string.IsNullOrEmpty(UserName))
			{
				return Json(new
				{
					Result = "没有指定要升级的会员！"
				});
			}
			try
			{
				if (_UsersService.AddToCompanyAdmin(UserName))
				{
					return Json(new
					{
						Result = "ok"
					});
				}
				else
				{
					return Json(new
					{
						Result = "升级失败！"
					});
				}
			}
			catch (Exception ex)
			{
				return Json(new
				{
					Result = "升级失败！" + ex.Message
				});
			}
		}
		/// <summary>
		/// 降为普通成员
		/// </summary>
		/// <param name="UserName"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,CompanyManage")]
		public IActionResult RemoveFromCompanyAdmin(string UserName)
		{
			if (string.IsNullOrEmpty(UserName))
			{
				return Json(new
				{
					Result = "没有指定要降级的会员！"
				});
			}
			try
			{
				if (_UsersService.RemoveFromCompanyAdmin(UserName))
				{
					return Json(new
					{
						Result = "ok"
					});
				}
				else
				{
					return Json(new
					{
						Result = "降级失败！"
					});
				}
			}
			catch (Exception ex)
			{
				return Json(new
				{
					Result = "降级失败！" + ex.Message
				});
			}
		}
		/// <summary>
		/// 批准加入
		/// </summary>
		/// <param name="UserName"></param>
		/// <param name="companyClientId"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,CompanyManage")]
		public IActionResult AgreeJoinCompany(string UserName, int companyClientId)
		{
			if (string.IsNullOrEmpty(UserName))
			{
				return Json(new
				{
					Result = "没有指定要批准加入的会员！"
				});
			}
			try
			{
				if (_UsersService.AgreeJoinCompany(UserName, companyClientId))
				{
					return Json(new
					{
						Result = "ok"
					});
				}
				else
				{
					return Json(new
					{
						Result = "批准加入失败！"
					});
				}
			}
			catch (Exception ex)
			{
				return Json(new
				{
					Result = "批准加入失败！" + ex.Message
				});
			}
		}
		/// <summary>
		/// 拒绝加入
		/// </summary>
		/// <param name="UserName"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateAntiForgeryToken]
		[AdminAuthorize(Roles = "SuperAdmin,CompanyManage")]
		public IActionResult RejectToCompany(string UserName)
		{
			if (string.IsNullOrEmpty(UserName))
			{
				return Json(new
				{
					Result = "移除失败！没有指定要移除的会员！"
				});
			}
			try
			{
				if (_UsersService.RemoveFromCompany(UserName))
				{
					return Json(new
					{
						Result = "ok"
					});
				}
				else
				{
					return Json(new
					{
						Result = "移除失败！"
					});
				}
			}
			catch (Exception ex)
			{
				return Json(new
				{
					Result = "移除失败！" + ex.Message
				});
			}
		}
		#endregion

		#region 辅助方法
		private IList<MenuEntity> InitSubMenu(XmlNode channelMenuNode)
		{
			IList<MenuEntity> menuEntityList = new List<MenuEntity>();
			if (channelMenuNode == null || !channelMenuNode.HasChildNodes)
				return menuEntityList;

			foreach (XmlNode menuNode in channelMenuNode)
			{
				string operateCode = XmlHelper.GetAttributesValue(menuNode, "operateCode");
				string NodeName = menuNode.Name;
				string id = XmlHelper.GetAttributesValue(menuNode, "id");
				string title = XmlHelper.GetAttributesValue(menuNode, "title");
				string Description = XmlHelper.GetAttributesValue(menuNode, "Description");
				string rightUrl = XmlHelper.GetAttributesValue(menuNode, "rightUrl");
				string MenuType = XmlHelper.GetAttributesValue(menuNode, "type");
				string MenuIcon = XmlHelper.GetAttributesValue(channelMenuNode, "icon");
				bool ShowOnForm = DataConverter.CBoolean(XmlHelper.GetAttributesValue(menuNode, "ShowOnForm"));
				bool ShowOnMenu = DataConverter.CBoolean(XmlHelper.GetAttributesValue(menuNode, "ShowOnMenu"));
				if (!ShowOnForm)
					continue;
				MenuEntity subMenuEntity = new MenuEntity
				{
					NodeName = NodeName,
					ID = id,
					Title = title,
					OperateCode = operateCode,
					Description = Description,
					Url = rightUrl,
					MenuType = MenuType,
					MenuIcon = MenuIcon,
					ShowOnForm = ShowOnForm,
					ShowOnMenu = ShowOnMenu
				};
				if (menuNode.HasChildNodes)
				{
					subMenuEntity.MenuItem = InitSubMenu(menuNode);
				}
				menuEntityList.Add(subMenuEntity);
			}
			return menuEntityList;
		}
		#endregion
	}
}